<?php

namespace Model;

use Daiyong\Db as db;
use Daiyong\Func as func;

class User extends Common {
    public $table = 'user';

    public function rule() {
        return array(
            'gid|must' => array('idInTable', '用户组未填写或输入错误', 'user_group'),
            'username|must' => array(
                array('only', '用户名与已有数据重复,请修改', $this->table),
                array('string', '用户名必须在2~10个字符之间', 2, 10),
                array('callback', function ($value) {
                    if (isPhone($value)) return '用户名不能为手机号';
                    if (isMail($value)) return '用户名不能为邮箱号';
                })
            ),
            'password|must' => array('string', '密码必须在6~20个字符之间', 6, 20),
            'phone' => array(
                array('phone', '请输入正确的手机号'),
                array('only', '手机号与已有数据重复,请修改', $this->table)
            ),
            'mail' => array(
                array('mail', '请输入正确的邮箱号'),
                array('only', '邮箱号与已有数据重复,请修改', $this->table)
            ),
        );
    }
    public function find($param) {
        $data = toArray(db::find($this->table, $param));
        if ($data['id']) {
            //删除不允许看到的信息
            unset($data['password']);
            unset($data['salt']);
            unset($data['token']);
            //加入用户组
            $groupModel = new \Model\UserGroup();
            $data['group'] = $groupModel->find(['id' => $data['gid']]);
        }
        return $data;
    }
    public function findAll($param = [], $orderBy = 'order by id desc', $limit = '') {
        $param = $this->findClear($param);
        $list = db::findAll($this->table, $param, $orderBy . ' ' . $limit);
        //加入用户组
        $newGroup = new \Model\UserGroup();
        $group = setKey($newGroup->findAll());
        foreach ($list as $k => $v) {
            //删除不允许看到的信息
            unset($list[$k]['password']);
            unset($list[$k]['salt']);
            unset($list[$k]['token']);
            $list[$k]['group'] = toArray(@$group[$v['gid']]);
        }
        return $list;
    }
    public function export($param = [], $orderBy = '') {
        //查询用户组信息
        $newGroup = new \Model\UserGroup();
        $group = $newGroup->findAll();
        //处理数据
        $title = ['id', '用户名', '用户组', '昵称', '邮箱', '注册时间'];
        $filePath = $this->exportExcel($title, function ($limit) use ($param, $orderBy, $group) {
            $list = $this->findAll($param, $orderBy, $limit);
            foreach ($list as $k => $v) {
                //行内容设置与$title一一对应
                $list[$k] = array($v['id'], $v['username'], @$group[$v['gid']]['name'], $v['nickname'], $v['mail'], $v['time_create']);
            }
            return $list;
        });
        return $filePath;
    }
    public function edit($data) {
        $verify = $this->verify($data, $this->rule());
        if ($verify !== true) {
            return $this->error($verify);
        }
        $data = $this->auto($data); //加入或去除一些自动生成的字段
        if ($data['id']) {
            $return = db::update($this->table, $data, ['id' => $data['id']]);
            $id = $data['id'];
        } else {
            $return = db::insert($this->table, $data);
            $id = $return;
        }
        if ($return) {
            $this->createSearchField($this->table, $id);
        }
        return $return;
    }
    public function delete($param) {
        if (!$param['id']) return $this->error('为避免错误请传入id删除');
        //开始删除
        return db::delete($this->table, $param);
    }
    private function auto($data) {
        if ($data['id']) {
            unset($data['time_create']);
            unset($data['date_create']);
        } else {
            $data['time_create'] = date('Y-m-d H:i:s');
            $data['date_create'] = date('Y-m-d');
        }
        if ($data['password']) {
            $data['salt'] = func::random(5);
            $data['password'] = md5($data['salt'] . $data['password'] . $data['salt']);
        }
        return $data;
    }
    //登陆
    public function login($param) {
        if ($param['username']) $sql = ['username' => $param['username']];
        if ($param['phone']) $sql = ['phone' => $param['phone']];
        if ($sql) $data = db::find($this->table, $sql);
        if ($data['id']) {
            if ($param['password']) { //密码登陆
                if ($data['password'] == md5($data['salt'] . $param['password'] . $data['salt'])) {
                    return $this->resetTokenAndReturn($data);
                } else {
                    return $this->error('密码错误');
                }
            } else if ($param['code']) { //手机验证码登陆
                if (!$param['codeTime']) return $this->error('请先获取验证码');
                if ((time() - $param['codeTime'] > 60 * 3)) { //3分钟内有效
                    return $this->error('验证码超时(3分钟类有效),请重新获取');
                }
                if ($param['codeMd5'] == $param['codeVerify']) {
                    return $this->resetTokenAndReturn($data);
                } else {
                    return $this->error('验证码错误');
                }
            } else {
                return $this->error('登陆方式错误');
            }
        } else {
            return $this->error('未找指定用户');
        }
    }
    //退出登陆
    public function loginOut($token) {
        return db::update($this->table, ['token' => ''], [
            'token' => $token
        ]);
    }
    //重置token与返回信息+token
    private function resetTokenAndReturn($data) {
        $token = md5($data['id'] . $data['username'] . $data['password'] . func::random(5));
        db::update($this->table, ['token' => $token], ['id' => $data['id']]);
        $loginInfo = $this->find(['id' => $data['id']]);
        $loginInfo['token'] = $token; //因为默认$this->find是删除了token的所以这里加上
        return $loginInfo;
    }
}
